package org.xhy.ruleengine.services;

import org.springframework.stereotype.Service;
import org.xhy.ruleengine.groovy.IGroovyClassLoader;
import org.xhy.ruleengine.tree.Node;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @gitee: https://gitee.com/XhyQAQ
 * @copyright: B站: https://space.bilibili.com/152686439
 * @Author: Xhy
 * @CreateTime: 2024-06-23 14:10
 */
public class MemoryDecisionTreeController implements IDecisionTreeController{

    IGroovyClassLoader iGroovyClassLoader;

    Map<String,Node> nodeMap;


    private Map<String,RuleEngine> ruleEngineMap;

    public MemoryDecisionTreeController(IGroovyClassLoader iGroovyClassLoader) {
        this.iGroovyClassLoader = iGroovyClassLoader;
        this.nodeMap = new HashMap<>();
        this.ruleEngineMap = new HashMap<>();
    }

    @Override
    public Collection<String> listKey() {
        return ruleEngineMap.keySet();
    }

    @Override
    public void save(String key,Node node){
        final Class aClass = iGroovyClassLoader.generateClass(node.getChildNodes());
        try {
            final Object o = aClass.newInstance();
            ruleEngineMap.put(key, (RuleEngine) o);
            nodeMap.put(key,node);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }
    @Override
    public void delete(String key){
        ruleEngineMap.remove(key);
        nodeMap.remove(key);
    }
    @Override
    public RuleEngine getRuleEngine(String key){
        return ruleEngineMap.get(key);
    }

    @Override
    public Node getNode(String key) {
        return nodeMap.get(key);
    }


}
